<script setup>
import mitt from '@/mitt'
import { storeToRefs } from 'pinia'
import { ref, onMounted } from 'vue'
import useUserStore from '@/pinia/userInfo'
import useGameStore from '@/pinia/gameStore'
import { Files, CircleCloseFilled } from '@element-plus/icons-vue'
import { userAlive } from '@/api/user'
import DialogTips from '../component/DialogTips.vue'
import BindDispatch from '../component/BindDispatch.vue'
import visitorLogin from '@/utils/visitor'
import GuideTips from '../component/GuideTips.vue'
const emits = defineEmits(['delList'])
const isClient = window.electronAPI || window.__TAURI__

const { token, showLoginDialog } = storeToRefs(useUserStore())
const { gameList, isMore, currentGameType } = storeToRefs(useGameStore())
const dialogVisible = ref(false)
const bindVisible = ref(false)
const title = ref('')
const dialogType = ref('open')
const loadingGame = ref(false)
const start_game_id = ref('') // 当前启动的游戏id
const start_type = ref('') // 当前启动游戏类型
const provider_id = ref('')
// eslint-disable-next-line no-unused-vars
const props = defineProps({
  _gameList: {
    type: Array,
    default: () => []
  },
  type: {
    type: String,
    default: ''
  }
})

onMounted(() => {
  window.addEventListener('storage', (event) => {
    if (!event.storageArea.isPlayGame) {
      dialogVisible.value = false
    }
  })
})

// 删除最近游戏
const delList = (item, index) => {
  emits('delList', item, index)
}

// 启动游戏

// 启动游戏
const showGame = (item) => {
  loadingGame.value = true
  start_game_id.value = item.content_id
  provider_id.value = item.provider_id
  start_type.value = JSON.parse(item.exe_param || '{}').start_type
  bindVisible.value = true
}
const startGame = async (item) => {
  if (token.value) {
    if (loadingGame.value) return
    const { code, data } = await userAlive()
    // 判断用户是否在线...
    if (code === 0 && data.alive) {
      showGame(item)
      // 判断游戏分类，如果网页游戏先不做处理
      // if (currentGameType.value.label === 'wangyeyouxi') {
      //   if (window.electronAPI) {
      //     window.electronAPI.sendMessage({
      //       type: 'openUrl',
      //       params: {
      //         url: exe_param.path
      //       }
      //     })
      //   } else {
      //     window.open(exe_param.path)
      //   }
      // }
    } else {
      window.localStorage.clear()
      window.sessionStorage.clear()
      token.value = ''
      start_game_id.value = ''
      if (isClient) {
        visitorLogin((type) => {
          type ? showGame(item) : (showLoginDialog.value = true)
        })
      } else {
        showLoginDialog.value = true
      }
    }
    setTimeout(() => {
      loadingGame.value = false
    }, 4000)
  } else {
    if (isClient) {
      visitorLogin((type) => {
        type ? showGame(item) : (showLoginDialog.value = true)
      })
    } else {
      showLoginDialog.value = true
    }
  }
}

// 获取游戏名称
const getRealName = (str) => {
  return str.replace(/\[[^\]]*\]/g, '')
}

// 加载更多游戏
const loadMore = () => {
  mitt.emit('loadMore')
}
</script>
<template>
  <div class="game-list py-[20px]">
    <!--绑定调度-->
    <BindDispatch
      :content_id="start_game_id"
      :start_type="start_type"
      :provider_id="provider_id"
      v-model="bindVisible"
      v-if="bindVisible"
    ></BindDispatch>
    <!--弹框提示-->
    <DialogTips
      @closeGame="closeGame"
      @openGame="openGame"
      :type="dialogType"
      :title="title"
      v-model="dialogVisible"
      v-if="dialogVisible"
    ></DialogTips>
    <div class="text-[#00c2ff] text-[16px] font-bold mt-[20px] flex justify-between items-center">
      <div>{{ currentGameType.name }}</div>
      <div><guide-tips></guide-tips></div>
    </div>
    <div
      class="bg-[#20222e] mt-[20px] h-[568px] rounded-md flex flex-col justify-center items-center"
      v-if="type == 'history' ? _gameList.length === 0 : gameList.length === 0"
    >
      <el-icon size="80" color="#666"><Files /></el-icon>
      <div class="text-[#666]">暂无游戏列表</div>
    </div>
    <div class="grid grid-cols-3 md:grid-cols-6 lg:grid-cols-10 gap-[20px] mt-[20px]">
      <div
        @click="startGame(item)"
        class="flex flex-col items-center relative justify-center bg-[#20222e] p-[0] hover:bg-[#222] group rounded-md overflow-hidden shadow-md cursor-pointer"
        v-for="(item, index) in type == 'history' ? _gameList : gameList"
        :key="index"
      >
        <!--启动moonlight游戏加载提示-->
        <div
          v-loading="true"
          element-loading-text="启动中..."
          v-if="start_game_id == item.content_id && loadingGame"
          element-loading-background="rgba(0, 0, 0, 0.3)"
          class="absolute bg-[#20222e] bg-opacity-60 z-10 w-[100%] h-[100%] flex justify-center items-center"
        ></div>
        <div
          @click.stop="delList(item, index)"
          v-if="type == 'history'"
          class="w-[30px] h-[25px] hidden absolute bg-[#20222e] rounded-bl-md right-0 top-0 z-[1] group-hover:flex items-center justify-center"
        >
          <el-icon size="20" color="#FFF"><CircleCloseFilled /></el-icon>
        </div>
        <div
          class="bg-no-repeat h-[0] origin-bottom bg-center pb-[80%] w-[100%] bg-cover group-hover:scale-[115%] transition-all"
          :style="{ backgroundImage: 'url(' + item.small_image + ')' }"
        ></div>
        <div class="py-[8px]">
          <div class="text-[12px] line-clamp-1 h-[20px]">
            {{ getRealName(item.name) }}
          </div>
        </div>
      </div>
    </div>
    <div class="flex justify-center text-[#999] mt-[30px]" v-if="!type && gameList.length > 0">
      <div class="cursor-pointer" v-if="isMore" @click="loadMore">加载更多游戏</div>
    </div>
  </div>
</template>
